package com.spzx.product.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.spzx.common.core.constant.ProductConstants;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.tree.TreeUtils;
import com.spzx.common.redis.service.RedisService;
import com.spzx.product.domain.Category;
import com.spzx.product.listener.CategoryExcelListener;
import com.spzx.product.mapper.CategoryMapper;
import com.spzx.product.service.CategoryService;
import com.spzx.product.vo.CategoryExcelVo;
import com.spzx.product.vo.CategoryVo;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private RedisService redisService;

    @Override
    public List<CategoryVo> treeSelect(Long id) {
        String cacheJson = redisService.getCacheObject(ProductConstants.PRODUCT_TREE_KEY + id);
        List<CategoryVo> list;
        if (StringUtils.hasText(cacheJson)) {
            list = JSON.parseObject(cacheJson, new TypeReference<List<CategoryVo>>() {
            });
        } else {
            list = categoryMapper.treeSelect(id);
            list.forEach(item -> {
                long count = categoryMapper.count(item.getId());
                item.setHasChildren(count > 0 ? true : false);
            });
            redisService.setCacheObject(
                    ProductConstants.PRODUCT_TREE_KEY + id,
                    JSON.toJSONString(list),
                    ProductConstants.PRODUCT_TREE_TTL,
                    TimeUnit.DAYS
            );
        }
        return list;
    }

    @Override
    public void exportData(HttpServletResponse response) {
        // 设置响应结果类型
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        try {
            // 这里URLEncoder.encode可以防止中文乱码
            String fileName = URLEncoder.encode("商品分类数据", "utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            // 查询全部商品信息
            List<Category> categoryList = categoryMapper.selectList();
            List<CategoryExcelVo> excelVos = categoryList.stream().map(item -> {
                CategoryExcelVo excelVo = new CategoryExcelVo();
                BeanUtils.copyProperties(item, excelVo);
                return excelVo;
            }).collect(Collectors.toList());
            // 将数据写到响应中
            EasyExcel.write(response.getOutputStream(), CategoryExcelVo.class)
                    .sheet()
                    .doWrite(excelVos);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("系统异常");
        }
    }

    @Override
    public void importData(MultipartFile file) {
        // 获取上传文件的原始文件名
        String originalFilename = file.getOriginalFilename();
        // 获取上传文件的后缀名
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
        // 判断文件后缀名是否是指定格式
        if (filenameExtension.equalsIgnoreCase("xls")
                || filenameExtension.equalsIgnoreCase("csv")
                || filenameExtension.equalsIgnoreCase("xlsx")) {
            try {
                EasyExcel.read(file.getInputStream())
                        .head(CategoryExcelVo.class)
                        .sheet()
                        .registerReadListener(new CategoryExcelListener(categoryMapper))
                        .doRead();
            } catch (IOException e) {
                throw new ServiceException("文件导入出现异常，请联系管理员");
            } finally {
                // 导入完成后，删除缓存
                Collection<String> keys = redisService.keys(ProductConstants.PRODUCT_TREE_KEY + "*");
                for (String key : keys) {
                    redisService.deleteObject(key);
                }
            }
        } else {
            throw new ServiceException("文件格式应当是：csv、xls或xlsx格式");
        }
    }

    @Override
    public List<CategoryVo> allTree() {
        List<Category> categoryList = categoryMapper.selectList();
        List<CategoryVo> vos = categoryList.stream().map(item -> {
            CategoryVo vo = new CategoryVo();
            vo.setId(item.getId());
            vo.setName(item.getName());
            vo.setImageUrl(item.getImageUrl());
            vo.setParentId(item.getParentId());
            return vo;
        }).collect(Collectors.toList());
        List<CategoryVo> resultList = TreeUtils.listTreeNodes(vos);
        return resultList;
    }
}
